package cn.arts.assumejson.algo.sort.class01;


import java.util.Arrays;

/**
 * In a sorted array, find the leftmost position of a number greater than or equal to a certain number
 *
 * @author by <a href="mailto:ligang941012@gmail.com">gang.Li</a>
 * @since 2024/7/31 0:01
 */
public class Code05_BSNearLeft {
    public static int findLeftMostIndex(int[] arr, int x) {
        if (arr == null || arr.length == 0) return -1;
        return process(arr, x, 0, arr.length - 1);
    }

    private static int process(int[] arr, int x, int L, int R) {
        int mid, index = -1;

        while (L <= R) {
            mid = L + ((R - L) >> 1);
            // find the leftmost position of a number greater than or equal to a certain number.
            if (arr[mid] >= x) {
                index = mid;
                R = mid - 1;
            } else {
                L = mid + 1;
            }
        }
        return index;
    }

    /////////////////////for test///////////////////
    public static int test(int[] arr, int x) {
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] >= x) {
                return i;
            }
        }
        return -1;
    }

    public static int[] generateRandomSortedArray(int maxValue, int maxSize) {
        int[] arr = new int[(int) ((maxSize + 1) * Math.random())];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = ((int) ((maxValue + 1) * Math.random()) - (int) ((maxValue + 1) * Math.random()));
        }
        Arrays.sort(arr);
        return arr;
    }

    public static void main(String[] args) {
        int testTime = 50000;
        int maxsize = 100;
        int maxValue = 100;
        boolean succeed = true;
        for (int i = 0; i < testTime; i++) {
            final int[] arr = generateRandomSortedArray(maxValue, maxsize);
            int randomValue = (int) ((maxValue + 1) * Math.random());
            if (test(arr, randomValue) != findLeftMostIndex(arr, randomValue)) {
                succeed = false;
                System.out.println(randomValue);
                System.out.println("test: " + test(arr, randomValue));
                System.out.println("findLeftMostIndex: " + findLeftMostIndex(arr, randomValue));
                System.out.println(Arrays.toString(arr));
                break;
            }
        }
        System.out.println(succeed ? "NICE!!!" : "FUCKING!!!!");
    }
}
